/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.tms.web;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.fee.entity.Cope;
import com.jeeplus.modules.fee.entity.NewRe;
import com.jeeplus.modules.fee.entity.Receivable;
import com.jeeplus.modules.fee.service.CopeService;
import com.jeeplus.modules.fee.service.NewReService;
import com.jeeplus.modules.fee.service.ReceivableService;
import com.jeeplus.modules.infor.entity.Price;
import com.jeeplus.modules.infor.entity.Settlement;
import com.jeeplus.modules.infor.service.PriceService;
import com.jeeplus.modules.infor.service.ProjectService;
import com.jeeplus.modules.infor.service.SettlementService;
import com.jeeplus.modules.infor.service.StartService;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.tms.entity.TmsYl;
import com.jeeplus.modules.tms.service.TmsYlService;

/**
 * 运量运费Controller
 * @author 李超辉
 * @version 2018-05-24
 */
@Controller
@RequestMapping(value = "${adminPath}/tms/tmsYl")
public class TmsYlController extends BaseController {

	@Autowired
	private TmsYlService tmsYlService;
	@Autowired
	private ReceivableService receivableService;
	@Autowired
	private ProjectService projectService;
	@Autowired
	private PriceService priceService;
	@Autowired
	private StartService startService;
	@Autowired
	private SettlementService settlementService;
	@Autowired
	private JdbcTemplate jdbc;
	@Autowired
	private CopeService copeService;
	@Autowired
	private NewReService newReService;
	
	@ModelAttribute
	public TmsYl get(@RequestParam(required=false) String id) {
		TmsYl entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = tmsYlService.get(id);
		}
		if (entity == null){
			entity = new TmsYl();
		}
		return entity;
	}
	@ResponseBody
	@RequestMapping(value="cx")
	public String cx(String min,String max,String pro,String jsd){
		if(min==""&max==""){
			return "";
		}
		if(pro!=null &&!pro.equals("")&&!pro.equals("undefined")){
			cha(min,max,pro,jsd);
		}else{
			cha(min,max,UserUtils.getUseroffice(),jsd);
		}
		return "";
	}

	public void cha(String min,String max,String pro,String jsd){
		NumberFormat nf = NumberFormat.getInstance();
		DecimalFormat df = new DecimalFormat("#.0");
		String sql;
		if(!pro.equals("总部")){
			sql="delete from tms_yl where pro='"+pro+"'";}else{
			sql="delete from tms_yl";
		}
		jdbc.execute(sql);

		NewRe r=new NewRe();

		if(!pro.equals("总部")){
			r.setProject(pro);
		}
		r.setMin(min);
		r.setMax(max);
		r.setArrive(jsd);
		List<NewRe> list=newReService.findList1(r);
		for(NewRe re:list){

				TmsYl y=new TmsYl();
				y.setPro(re.getProject());
				y.setQyd(re.getStart());
				y.setJsd(re.getArrive());
				y.setXl(re.getStart()+"-"+re.getArrive());
				y.setQj1(re.getWidth());
				String weight=re.getWeight();
				y.setYf1(nf.format(re.getZyf()));
				y.setYsfy1(nf.format(re.getFreight()));
				y.setYl1(nf.format(weight));
				double ysdj=Double.parseDouble(re.getZyf())/Double.parseDouble(weight);
				double jsdj=Double.parseDouble(re.getFreight())/Double.parseDouble(weight);
                y.setDj1(nf.format(ysdj));
                y.setYsdj1(nf.format(jsdj));
				tmsYlService.save(y);
		}
	}
	/**
	 * 运量运费列表页面
	 */
	@RequiresPermissions("tms:tmsYl:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/tms/tmsYlList";
	}
	
		/**
	 * 运量运费列表数据
	 */
	@ResponseBody
	@RequiresPermissions("tms:tmsYl:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(TmsYl tmsYl, HttpServletRequest request, HttpServletResponse response, Model model) {
		String pro=UserUtils.getUseroffice();
		if(!pro.equals("总部")){
			tmsYl.setPro(pro);
		}
		Page<TmsYl> page = tmsYlService.findPage(new Page<TmsYl>(request, response), tmsYl);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑运量运费表单页面
	 */
	@RequiresPermissions(value={"tms:tmsYl:view","tms:tmsYl:add","tms:tmsYl:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(TmsYl tmsYl, Model model) {
		model.addAttribute("tmsYl", tmsYl);
		return "modules/tms/tmsYlForm";
	}

	/**
	 * 保存运量运费
	 */
	@ResponseBody
	@RequiresPermissions(value={"tms:tmsYl:add","tms:tmsYl:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(TmsYl tmsYl, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, tmsYl)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		tmsYlService.save(tmsYl);//新建或者编辑保存
		j.setSuccess(true);
		j.setMsg("保存运量运费成功");
		return j;
	}
	
	/**
	 * 删除运量运费
	 */
	@ResponseBody
	@RequiresPermissions("tms:tmsYl:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(TmsYl tmsYl, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		tmsYlService.delete(tmsYl);
		j.setMsg("删除运量运费成功");
		return j;
	}
	
	/**
	 * 批量删除运量运费
	 */
	@ResponseBody
	@RequiresPermissions("tms:tmsYl:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			tmsYlService.delete(tmsYlService.get(id));
		}
		j.setMsg("删除运量运费成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("tms:tmsYl:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(TmsYl tmsYl, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "运量运费"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<TmsYl> page = tmsYlService.findPage(new Page<TmsYl>(request, response, -1), tmsYl);
    		new ExportExcel("运量运费", TmsYl.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出运量运费记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("tms:tmsYl:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<TmsYl> list = ei.getDataList(TmsYl.class);
			for (TmsYl tmsYl : list){
				try{
					tmsYlService.save(tmsYl);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条运量运费记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条运量运费记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入运量运费失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/tms/tmsYl/?repage";
    }
	
	/**
	 * 下载导入运量运费数据模板
	 */
	@RequiresPermissions("tms:tmsYl:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "运量运费数据导入模板.xlsx";
    		List<TmsYl> list = Lists.newArrayList(); 
    		new ExportExcel("运量运费数据", TmsYl.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/tms/tmsYl/?repage";
    }

}